package cn.tworice.log.web;


import cn.tworice.common.vo.StateCodeConst;
import cn.tworice.log.dao.po.OperationLogDO;
import cn.tworice.log.dao.po.LoginLogDO;
import cn.tworice.common.vo.RequestResult;
import cn.tworice.log.constand.ExportConst;
import cn.tworice.log.service.LogService;
import cn.tworice.mybatis.vo.PageParam;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

/**
 * 日志管理
 *
 */
@RestController
@RequestMapping("admin/log")
@Slf4j
@CrossOrigin
@Api(tags = "系统日志")
public class LogController {
    @Resource
    private LogService logService;

    /**
     * 获取操作日志
     * @param pageParam 分页
     */
    @GetMapping("adminList")
    @ApiOperation("获取操作日志")
    public RequestResult adminList(PageParam pageParam, OperationLogDO entity) {
        return RequestResult.success().setData(logService.getPage(pageParam,entity));
    }

    @DeleteMapping("delAdmin")
    @ApiOperation("删除操作日志")
    public RequestResult delAdmin(String[] id){
        logService.removeByIds(Arrays.asList(id));
        return RequestResult.success("删除" + id.length + "条操作日志");
    }

    @GetMapping("loginList")
    @ApiOperation("登录日志")
    public RequestResult loginList(PageParam pageParam, LoginLogDO entity){
        return RequestResult.success()
                .setData(logService.getLoginLogPage(pageParam,entity));
    }

    @PutMapping("recover")
    public RequestResult recover(String id) {
        return RequestResult.success(StateCodeConst.MESSAGE,logService.recover(id));
    }

    @GetMapping("exportOperation")
    @ApiOperation("导出操作日志")
    public void export(Integer type, String[] id,HttpServletResponse response) throws IOException {
        List<OperationLogDO> adminList = null;
        if(ExportConst.ALL.equals(type)){
            // 全部导出
            // 查询数据列表
            adminList = logService.list();
        } else if (id != null && id.length > 0) {
            // TODO 导出选中
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("模板", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), OperationLogDO.class).sheet("操作日志")
                .doWrite(adminList);
    }
}
